import { sys, director, assetManager, Prefab, Material, Node, AssetManager } from 'cc';

export default class Util {

    static return2DGame() 
    {
        const scene: any = director.getScene();
        const canvas: any = scene.getChildByName('Canvas');
        // console.log("return2DGame",canvas);
        canvas.active = true;
        let node3d = scene.getChildByName('3DSceneRoot');
        if(node3d)
        {
            node3d.removeFromParent();
        }
    }

    static loadPerfab(resPath: string, callback: (prefab: any) => void) 
    {
        const bundleName: string = 'mahjong3d';
        assetManager.loadBundle(bundleName, (err, bundle) => {
            if (err) {
                console.error('Failed to load bundle:', err);
                return null;
            }
            // console.log('Bundle loaded:', bundle);

            // 加载具体资源
            bundle.load(resPath, Prefab, (err, prefab) => {
                if (err) {
                    console.error('Failed to load prefab:', err);
                    return null;
                }
                // console.log('Prefab successfully loaded!');
                callback(prefab);
                return prefab;
            });
        });

		return null;
    }

    static loadMaterial(resPath: string, callback: (material: any) => void) 
    {
        const bundleName: string = 'mahjong3d';
        assetManager.loadBundle(bundleName, (err, bundle) => {
            if (err) {
                console.error('Failed to load bundle:', err);
                return null;
            }
            // console.log('Bundle loaded:', bundle);

            // 加载具体资源
            bundle.load(resPath, Material, (err, material) => {
                if (err) {
                    console.error('Failed to load material:', err);
                    return null;
                }
                // console.log('Prefab successfully loaded!');
                callback(material);
                return material;
            });
        });

		return null;
    }

    static setLayerRecursively(node: Node, layer: number): void {
        node.layer = layer;  // 设置当前节点的 layer
        // 遍历所有子节点并递归调用
        node.children.forEach(child => {
            this.setLayerRecursively(child, layer);
        });
    }

    static getRandomNumber(min: number, max: number): number {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    static randomCardID(){
        let type = this.getRandomNumber(1, 4);
        let value = type == 4 ? this.getRandomNumber(1, 7) : this.getRandomNumber(1, 9);
        let index = this.getRandomNumber(0, 9);
        let cardID = type * 100 + value * 10 + index;
        return cardID;
    }


}